﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class Drivers : ClassManager.SessionManagerPage
    {

        private void GetAllDriversByCompany(int companyId)
        {
            try
            {
                DriversGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.DriversProvider.GetByCompanyID(companyId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private GPSTrackingDBV2.Entities.Drivers Invoke_Entity(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.Drivers DriverEntity = new GPSTrackingDBV2.Entities.Drivers();
            try
            {
                DriverEntity.DriverId = int.Parse(Entity[GPSTrackingDBV2.Entities.DriversColumn.DriverId.ToString()].ToString()); //int.Parse(Entity[GPSTrackingDBV2.Entities.DriversColumn.DriverId.ToString()]);
                DriverEntity.Identification = Convert.ToString(Entity[GPSTrackingDBV2.Entities.DriversColumn.Identification.ToString()]);
                DriverEntity.DriverName = Convert.ToString(Entity[GPSTrackingDBV2.Entities.DriversColumn.DriverName.ToString()]);
                DriverEntity.Name = Convert.ToString(Entity[GPSTrackingDBV2.Entities.DriversColumn.Name.ToString()]);
                DriverEntity.FirstSurname = Convert.ToString(Entity[GPSTrackingDBV2.Entities.DriversColumn.FirstSurname.ToString()]);
                DriverEntity.SecondSurname = Convert.ToString(Entity[GPSTrackingDBV2.Entities.DriversColumn.SecondSurname.ToString()]);
                DriverEntity.Phone = Convert.ToString(Entity[GPSTrackingDBV2.Entities.DriversColumn.Phone.ToString()]);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return DriverEntity;

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.DriversColumn.DriverName.ToString();
                expression.SetSortOrder("Ascending");
                this.DriversGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }
        
        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        protected void DriversGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                GetAllDriversByCompany(getSessionManager().CompanyIDSelectedComboBox);
                DriversGrid.Height = Unit.Parse(HiddenFieldHeight.Value.ToString());
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo cargar la información de los choferes.");
            }
        }

        protected void DriversGrid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Drivers DriverEntity = Invoke_Entity(Entity);
                DriverEntity.OriginalDriverId = DriverEntity.DriverId;

                GPSTrackingDBV2.Data.DataRepository.DriversProvider.Update(DriverEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo actualizar la información del chofer.");
            }
        }

        protected void DriversGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Drivers DriverEntity = Invoke_Entity(Entity);

                GPSTrackingDBV2.Data.DataRepository.DriversByCompaniesProvider.Delete(tm, getSessionManager().CompanyIDSelectedComboBox, DriverEntity.DriverId);

                GPSTrackingDBV2.Data.DataRepository.DriversProvider.Delete(tm, DriverEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);            
                if(ex.Message.Contains("UsersByGPSGroups"))
                    showErrorMessage("No se puede eliminar el usuario porque esta asociado a un grupo de usuarios, debe quitar la asociación y volver a eliminar el usuario correspondiente.");
                showErrorMessage("No se puede eliminar el usuario porque esta asociado a otros registros.");                   
            }
        }

        protected void DriversGrid_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                Entity["DriverId"] = GPSTrackingDBV2Custom.Data.DataRepository.DriverProvider.GetNextID();

                GPSTrackingDBV2.Entities.Drivers DriverEntity = Invoke_Entity(Entity);
                GPSTrackingDBV2.Entities.DriversByCompanies DriverByCompaniesEntity = new GPSTrackingDBV2.Entities.DriversByCompanies();
                
                GPSTrackingDBV2.Data.DataRepository.DriversProvider.Insert(tm, DriverEntity);

                DriverByCompaniesEntity.CompanyId = getSessionManager().CompanyIDSelectedComboBox;
                DriverByCompaniesEntity.DriverId = DriverEntity.DriverId;

                GPSTrackingDBV2.Data.DataRepository.DriversByCompaniesProvider.Insert(tm, DriverByCompaniesEntity);
                               
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo registrar el chofer.");
            }
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Choferes...');", true);
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            DriversGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in DriversGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
                else
                {
                    if (column is GridCheckBoxColumn)
                    {
                        GridCheckBoxColumn boundCheckColumn = column as GridCheckBoxColumn;
                        boundCheckColumn.CurrentFilterValue = "true";
                    }
                }
            }
            DriversGrid.MasterTableView.Rebind();
        }

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }
    }
}